<template>
  <van-list
    class="follow-list"
    v-model:loading="loading"
    :finished="finished"
    finished-text="没有更多了"
    @load="onLoad"
  >
    <div class="list">
      <div class="list-item" v-for="follow in follows" :key="follow.id">
        <!-- 用户信息区域 -->
        <div class="user-info-section">
          <div class="user-left">
            <img :src="proxyImageUrl(follow.u.p)" class="user-avatar" />
          </div>
          <div class="user-right">
            <div class="user-name">
              {{ follow.u.n }} <span class="user-level">Lv.{{ follow.u.lv }}</span>
            </div>
            <div class="user-stats">
              <span class="followers">{{ follow.u.followers_count_text }}</span>
              <span class="recipes">{{ follow.u.recipes_count_text }}</span>
            </div>
          </div>
          <div class="follow-action">
            <van-button
              class="follow-btn"
              size="small"
              :type="follow.u.is_followed ? 'default' : 'primary'"
              @click="toggleFollow(follow)"
            >
              {{ follow.u.is_followed ? '已关注' : '关注' }}
            </van-button>
          </div>
        </div>

        <!-- 菜品图片/视频-->
        <div class="dish-image">
          <template v-if="follow.video_url != ''">
            <!-- <img :src="proxyImageUrl(follow.img)" class="dish-img" /> -->
            <video
              class="dish-img"
              :ref="(el) => setVideoRef(el, follow.id)"
              autoplay
              :muted="isMuted"
              @loadeddata="onVideoLoaded"
            >
              <source :src="follow.video_url" type="application/x-mpegURL" />
            </video>

            <!-- 静音按钮（Vant Icon + 自定义样式） -->
            <van-button
              v-if="showMuteButton"
              class="mute-btn"
              :icon="isMuted ? 'volume-off' : 'volume'"
              :class="{ 'mute-btn--muted': isMuted }"
              @click="toggleMute(follow.id)"
            />
          </template>

          <template v-else>
            <img :src="proxyImageUrl(follow.img)" class="dish-img" />
          </template>
        </div>

        <!-- 帖子信息 -->
        <div class="post-section">
          <div class="post-header">
            <div class="collections-info">
              <div
                class="collectors"
                v-if="follow.collect_users && follow.collect_users.length > 0"
              >
                <template v-for="(collector, index) in follow.collect_users" :key="index">
                  <img :src="proxyImageUrl(collector.p)" class="collector-avatar" />
                </template>
              </div>
              <span class="collect-count">{{ follow.collect_count_text }}</span>
            </div>
            <div class="social-actions">
              <van-icon name="star-o" class="social-icon" />
              <van-icon name="comment-o" class="social-icon" />
              <van-icon name="share-o" class="social-icon" />
            </div>
          </div>

          <div class="post-title">{{ follow.t }}</div>

          <!-- 话题 -->
          <div class="topic" v-if="follow.events && follow.events.length > 0">
            <template v-for="(event, index) in follow.events" :key="index">
              <p><img :src="hashTag" class="hashTag" />{{ event.c }}</p>
            </template>
          </div>
        </div>
      </div>
    </div>
  </van-list>
</template>

<script setup>
import hashTag from '@/assets/hashTag.png'
import Hls from 'hls.js'
import { ref, onMounted, computed, useTemplateRef } from 'vue'
import { fetchFollowList } from '@/api/index.js'
import { proxyImageUrl } from '@/tool/index.js'
const loading = ref(true)
const finished = ref(false)
const follows = ref([])

const pageNumber = ref(1)
const limit = ref(20)
const offset = computed(() => {
  return (pageNumber.value - 1) * limit.value
})

//当前返回列表数量
const currentResponseLength = ref(0)

// 视频元素引用映射
const videoRefs = ref(new Map())

// 设置视频引用
const setVideoRef = (el, id) => {
  if (el) {
    videoRefs.value.set(id, el)
  }
}

// 视频控制相关
const isMuted = ref(true) // 是否静音
const showMuteButton = ref(false) // 控制按钮是否显示（等视频加载后才显示）

onMounted(async () => {
  await initLoad(offset.value, limit.value)
  // 为所有视频元素初始化 HLS（如果浏览器不支持原生 HLS）
  videoRefs.value.forEach((video, id) => {
    if (Hls.isSupported()) {
      console.log('Hls.isSupported()', Hls.isSupported())
      const hls = new Hls()
      hls.loadSource(video.querySelector('source').src)
      hls.attachMedia(video)
    }
  })
})

// 初始化加载
const initLoad = async (offset, limit) => {
  await getFollowList(offset, limit)
}

// 加载更多
const onLoad = async () => {
  if (finished.value) {
    loading.value = false
    return
  }
  pageNumber.value++
  await getFollowList(offset.value, limit.value)
}

// 关注列表
const getFollowList = async (offset, limit) => {
  try {
    loading.value = true
    const {
      state,
      result: { rfs },
    } = await fetchFollowList(offset, limit)
    if (state === 'success') {
      if (rfs.length > 0) {
        if (pageNumber.value === 1) {
          follows.value = rfs
        } else {
          follows.value = [...follows.value, ...rfs]
        }
      }
      currentResponseLength.value = rfs.length

      // 如果返回的数据量小于 limit 或为0，表示没有更多数据
      finished.value =
        currentResponseLength.value === 0 || currentResponseLength.value < limit.value
    }
  } catch (error) {
    console.log('获取关注列表错误:', error)
    pageNumber.value--
  } finally {
    loading.value = false
  }
}

// 关注/取消关注
const toggleFollow = (follow) => {
  follow.u.is_followed = !follow.u.is_followed
}

//参与活动
const goToEvent = (url) => {
  // url是外部链接，需要打开这个url
  window.open(url)
}

// 视频加载完成后显示静音按钮
const onVideoLoaded = () => {
  showMuteButton.value = true
}

// 切换静音状态
const toggleMute = (id) => {
  const video = videoRefs.value.get(id)
  if (video) {
    video.muted = !video.muted
    isMuted.value = video.muted
  }
}
</script>

<style scoped lang="scss">
.follow-list {
  min-height: 100vh;
  background-color: #f5f5f5;

  :deep(.van-list__finished-text) {
    padding-bottom: 50px; // 避免被底部TabBar遮挡
  }

  .list {
    // padding: 0 12px;

    .list-item {
      background: #fff;
      // border-radius: 12px;
      margin: 12px 0;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      overflow: hidden;

      .user-info-section {
        display: flex;
        align-items: center;
        padding: 12px 10px;
        border-bottom: 1px solid #f0f0f0;

        .user-left {
          .user-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
          }
        }

        .user-right {
          flex: 1;
          margin-left: 12px;

          .user-name {
            font-size: 14px;
            font-weight: 500;
            color: #333;
            margin-bottom: 4px;

            .user-level {
              font-size: 12px;
              color: #ff6b35;
              // background: #fff0e8;
              padding: 1px 6px;
              border-radius: 10px;
              // margin-left: 6px;
            }
          }

          .user-stats {
            font-size: 12px;
            color: #999;

            .followers,
            .recipes {
              margin-right: 12px;
            }
          }
        }

        .follow-action {
          .follow-btn {
            min-width: 60px;
            height: 28px;
            border-radius: 14px;
            font-size: 12px;
            border: none;

            &.van-button--primary {
              background: #ff4d4f;
              color: #fff;
            }

            &.van-button--default {
              background: #f5f5f5;
              color: #999;
              border: 1px solid #e0e0e0;
            }
          }
        }
      }

      .dish-image {
        position: relative;

        .dish-img {
          width: 100%;
          height: auto;
          aspect-ratio: 4/3;
          object-fit: cover;
        }

        .mute-btn {
          position: absolute;
          bottom: 10px;
          right: 10px;
          width: 20px;
          height: 20px;
          border-radius: 50%;
          background-color: rgba(0, 0, 0, 0.6);
          color: #fff;
          font-size: 18px;
          padding: 0;
          display: flex;
          align-items: center;
          justify-content: center;
          border: none;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
          z-index: 10;

          &:hover {
            background-color: rgba(0, 0, 0, 0.8);
            transform: scale(1.05);
            transition: all 0.2s ease;
          }

          &--muted {
            background-color: rgba(0, 0, 0, 0.8);

            .van-icon {
              filter: invert(1) brightness(0.5);
            }
          }

          .van-icon {
            font-size: 18px;
            margin: 0;
            line-height: 1;
          }
        }
      }

      .post-section {
        padding: 16px 10px;

        .post-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .collections-info {
            display: flex;
            align-items: center;

            .collectors {
              display: flex;
              align-items: center;
              margin-right: 10px;

              .collector-avatar {
                width: 20px;
                height: 20px;
                border-radius: 50%;
                object-fit: cover;
                margin-right: -6px;
                border: 1px solid #fff;

                &:first-child {
                  margin-right: 4px;
                }
              }
            }

            .collect-count {
              font-size: 12px;
              color: #999;
              // margin-left: 8px;
            }
          }

          .social-actions {
            display: flex;
            align-items: center;
            gap: 16px;

            .social-icon {
              font-size: 18px;
              color: #999;

              &:hover {
                color: #ff4d4f;
              }
            }
          }
        }

        .post-title {
          font-size: 16px;
          font-weight: 500;
          color: #333;
          line-height: 1.4;
          margin-bottom: 8px;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }

        .topic {
          font-size: 12px;
          margin-bottom: 5px;
          color: #87ceeb;
          line-height: 1.4;

          p {
            margin: 0;
            padding: 5px 0;
            display: inline-block;

            .hashTag {
              width: 12px;
              height: 12px;
              margin-right: 4px;
              vertical-align: middle;
              // filter: invert(0.5) brightness(1.2);
              // opacity: 0.8;
            }
          }
        }
      }
    }
  }
}
</style>
